#!/usr/bin/python
#-*-coding:utf-8-*-

import itertools
import MySQLdb

class DbUtils():
    
    def __init__(self, dbconf=None):
        if not dbconf:
            dbconf = {
                    "host": "127.0.0.1",
                    "user": "root",
                    "passwd": "123456",
                    "db": "gaodeha",
                    "port": 3306,
                    "charset": "utf8",
                    "use_unicode": False
             }
        self.connector = MySQLdb.connect(**dbconf) 
        self.connector.autocommit(True)
        self.cursor = self.connector.cursor()


    def fetchOneDict(self, sql, params=None):
        self.executeSql(sql, params)
        columns = [d[0].lower() for d in self.cursor.description]
        data = self.cursor.fetchone()
        if data:
            return dict(itertools.izip(columns, data))

    def fetchOneRaw(self, sql, params=None):
        self.executeSql(sql, params)
        return self.cursor.fetchone()


    def fetchManyDict(self, sql, params=None):
        self.executeSql(sql, params)
        columns = [d[0].lower() for d in self.cursor.description]
        while True:
            rows = self.cursor.fetchmany(50)
            if not rows:
                return
            for row in rows:
                yield dict(itertools.izip(columns, row))

    def fetchManyRaw(self, sql, params=None):
        self.executeSql(sql, params)
        while True:
            rows = self.cursor.fetchmany(50)
            if not rows:
                return
            for row in rows:
                yield row

    def executeSql(self, sql, params=None):
        if params:
            self.cursor.execute(sql, params)
        else:
            self.cursor.execute(sql)


    def insertSql(self, sql, params=None):
        self.executeSql(sql, params)
        return self.cursor.lastrowid

    def close(self):
        try:
            self.cursor.close()
            self.connector.close()
        except Exception as e:
            pass


    def __del__(self):
        self.close()





def main():
    db = DbUtils()
    count = db.fetchOneRaw("select count(*) from tb_category")
    print "count:" + str(count[0])
    


if __name__ == "__main__":
    main()
